package com.ruoyi.wechat.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.WxContentSecurityUtil;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.degree.domain.WechatUser;
import com.ruoyi.degree.service.IBizSchoolsService;
import com.ruoyi.degree.service.IWechatUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.utils.ServletUtils.getRequest;

@RestController
@RequestMapping("/wxapi/user")
@Api(tags = "微信用户API", description = "微信用户相关接口")
public class WechatUserApi extends BaseApi  {

    @Autowired
    private IBizSchoolsService bizSchoolsService;

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;
    @Autowired
    private IWechatUserService iWechatUserService;


    //用户登录
    @ApiOperation("用户登录")
    @Anonymous
    @PostMapping("/userReg")
    public AjaxResult userReg(@RequestBody Map<String, String> params) {
        // 通过query获取code
        //根据post请求获取code和phoneCode
        String code = params.get("code");
        String phoneCode = params.get("phoneCode");
        if (code == null || code.isEmpty()) {
            return AjaxResult.error("code不能为空");
        }

        if (phoneCode == null || phoneCode.isEmpty()) {
            return AjaxResult.error("phoneCode不能为空");
        }
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid
                + "&secret=" + secret
                + "&js_code=" + code
                + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);

        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode;
        String openid="";
        String phoneNum="";
        try {
            jsonNode = mapper.readTree(response);
            openid = jsonNode.has("openid") ? jsonNode.get("openid").asText() : null;
            phoneNum = getPhoneNumberByCode(phoneCode);
        } catch (Exception e) {
            return AjaxResult.error()
                    .put("message", "获取用户信息失败")
                    .put("error", e.getMessage());
        }

        //根据openId 去数据库查询是否存在该用户
        WechatUser user = new WechatUser();
        user.setOpenId(openid);
        List<WechatUser> list = iWechatUserService.selectWechatUserList(user);
        if(list!=null  && list.size()==1) {
            return AjaxResult.success()
                    .put("userInfo", list.get(0));
        }else{
            //如果不存在该用户，则新增
            WechatUser wxUser = new WechatUser();
            wxUser.setOpenId(openid);
            wxUser.setMobile(phoneNum);
            iWechatUserService.insertWechatUser(wxUser);
            return AjaxResult.success()
                    .put("userInfo", wxUser);
        }


    }


    public String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        JsonNode jsonNode = null;
        try {
            jsonNode = new ObjectMapper().readTree(response);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return jsonNode.has("access_token") ? jsonNode.get("access_token").asText() : null;
    }

    public String getPhoneNumberByCode(String code) throws Exception {
        String accessToken = getAccessToken();
        if (accessToken == null) return "access_token获取失败";

        String url = String.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s", accessToken);

        // 构造请求体
        ObjectMapper mapper = new ObjectMapper();
        String requestBody = mapper.writeValueAsString(Collections.singletonMap("code", code));

        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForObject(url, requestBody, String.class);

        JsonNode jsonNode = mapper.readTree(response);
        JsonNode phoneInfo = jsonNode.path("phone_info");
        return phoneInfo.has("phoneNumber") ? phoneInfo.get("phoneNumber").asText() : "未获取到手机号";
    }

    //uploadAvatar
    @ApiOperation("上传用户头像")
    @Anonymous
    @PostMapping("/uploadAvatar")
    public AjaxResult uploadAvatar(@RequestParam("file") MultipartFile file,
                                   @RequestParam("openid") String openid) {
        if (file.isEmpty()) {
            return AjaxResult.error("上传文件不能为空");
        }
        if (openid == null) {
            return AjaxResult.error("openid不能为空");
        }
        String fileName="";
        try {
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileUrl = FileUploadUtils.upload(filePath, file);
            // 这里返回一个示例结果
            return AjaxResult.success()
                    .put("message", "头像上传成功")
                    .put("avatar", fileUrl); // 替换为实际保存的头像路径或URL
        } catch (Exception e) {
            return AjaxResult.error("文件上传失败：" + e.getMessage());
        }

    }

    //更新用户信息 updateUserInfo
    @ApiOperation("更新用户信息")
    @Anonymous
    @PostMapping("/updateUserInfo")
    public AjaxResult updateUserInfo(@RequestBody WechatUser user) {
        if (user.getId() == null) {
            return AjaxResult.error("openid不能为空");
        }
        WechatUser existingUser = iWechatUserService.selectWechatUserById(user.getId());
        if (existingUser == null) {
            return AjaxResult.error("用户不存在");
        }

        // 获取 accessToken
        String accessToken = getAccessToken();

        // 校验昵称文本安全
        boolean nicknameSafe = WxContentSecurityUtil.checkText(accessToken, user.getNickname());
        if (!nicknameSafe) {
            return AjaxResult.error("昵称内容不安全，请更换后再提交！");
        }

        // 校验头像图片安全
        boolean avatarSafe = WxContentSecurityUtil.checkMedia(accessToken, user.getAvatarUrl(), 2);
        if (!avatarSafe) {
            return AjaxResult.error("头像内容不安全，请更换后再提交！");
        }
        // 更新用户信息
        existingUser.setNickname(user.getNickname());
        existingUser.setAvatarUrl(user.getAvatarUrl());
        iWechatUserService.updateWechatUser(existingUser);
        return AjaxResult.success()
                .put("message", "用户信息更新成功")
                .put("userInfo", existingUser);
    }
    //写一个下载
    public void downloadAvatar(String avatarUrl) {
        // 这里可以使用RestTemplate或其他HTTP客户端库来下载图片
        // 下载后可以保存到本地文件系统或数据库
    }
}
